﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Mystery.SharePoint
{
	/// <summary>
	/// Extension methods for SPEventReceiverDefinitionCollection
	/// </summary>
	public static class SPEventReceiverDefinitionCollectionExtensions
	{
		/// <summary>
		/// Adds an event handler entry to the collection
		/// </summary>
		/// <param name="collection"></param>
		/// <param name="eventType">The type of event we are adding</param>
		/// <param name="receiver">The type of the receiver implementing the hander</param>
		/// <param name="sequenceNumber">The sequence number of the handler. Numbers under 10000 will automatically be move to a range above 10000</param>
		public static void Add(this SPEventReceiverDefinitionCollection collection, SPEventReceiverType eventType, Type receiver, int sequenceNumber)
		{
			if (collection == null) throw new ArgumentNullException("collection");
			if (receiver == null) throw new ArgumentNullException("receiver");

			collection.Add(eventType, receiver, sequenceNumber, SPEventReceiverSynchronization.Default);
		}

		/// <summary>
		/// Adds an event handler entry to the collection
		/// </summary>
		/// <param name="collection"></param>
		/// <param name="eventType">The type of event we are adding</param>
		/// <param name="receiver">The type of the receiver implementing the hander</param>
		/// <param name="sequenceNumber">The sequence number of the handler. Numbers under 10000 will automatically be move to a range above 10000</param>
		/// <param name="synchronization">Specifies what type of synchronization should be applied</param>
		public static void Add(this SPEventReceiverDefinitionCollection collection, SPEventReceiverType eventType, Type receiver, int sequenceNumber,
							   SPEventReceiverSynchronization synchronization)
		{
			if (collection == null) throw new ArgumentNullException("collection");
			if (receiver == null) throw new ArgumentNullException("receiver");

			// SharePoint has a reserved range, move it above that
			int sequence = (sequenceNumber < 10000) ? sequenceNumber + 10000 : sequenceNumber;

			// check if it already exists
			foreach (SPEventReceiverDefinition receiverDefinition in collection)
			{
				if ((receiverDefinition.Class == receiver.FullName) &&
					(receiverDefinition.Type == eventType))
				{
					return;
				}
			}
			// if we get this far, it doesn't exist.
			SPEventReceiverDefinition definition = collection.Add();
			definition.Assembly = receiver.Assembly.FullName;
			definition.Class = receiver.FullName;
			definition.Type = eventType;
			definition.SequenceNumber = sequence;
			definition.Synchronization = synchronization;
			definition.Update();
		}
	}
}
